package info.wegosoft.android.activity;

import info.wegosoft.R;
import info.wegosoft.android.adapter.MBlogArrayAdapter;
import info.wegosoft.android.model.MBlog;
import info.wegosoft.android.model.Platform;
import info.wegosoft.android.qauth.sina.OAuthConstant;
import info.wegosoft.android.qauth.sina.Weibo;
import info.wegosoft.android.qauth.sina.WeiboException;
import info.wegosoft.android.qauth.tencent.OAuth;
import info.wegosoft.android.qauth.tencent.QWeiboSyncApi;
import info.wegosoft.android.qauth.tencent.QWeiboType.PageFlag;
import info.wegosoft.android.qauth.tencent.QWeiboType.ResultType;
import info.wegosoft.android.util.CacheUtil;
import info.wegosoft.android.util.TimeUtil;

import java.io.FileOutputStream;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * Filename:    MBlogListActivity.java 
 * Package:     info.wegosoft.android.activity 
 * Description: TODO(这里用一句话描述这个类的作用)
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-5-10 下午04:06:15
 */
public class MBlogListActivity extends ListActivity {

	private MBlogArrayAdapter arrayAdapter = null;
	private List<MBlog> mblogList = null;
	private ImageButton writeButton;
	private ImageButton refreshButton;
	private TextView userNameTextView;
	private TextView firstStateText;
	private TextView lastStateText;
	private ProgressBar firstLoading;
	private ProgressBar lastLoading;	
	private UIHandler handler;
	private LinearLayout lastRowView;
	private int platformType;
	//第一行是否正在刷新的标志
	private boolean isRefreshing = false;
	//第一行是否正在载入更多的标志
	private boolean isLoading = false;
	
	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.mblog_list);
		
		setTitle("WeGo微博平台");
			
		handler = new UIHandler();
		
		platformType = this.getSharedPreferences("platform",Context.MODE_PRIVATE).getInt("type", -1);
		
		userNameTextView = (TextView) findViewById(R.id.userNameTv);
		
		switch (platformType) {
			case Platform.SINA_PLATFORM:
				 
				 userNameTextView.setText(getSharedPreferences("sina_qauth",Context.MODE_PRIVATE).getString("userName", ""));
				 
				 break;
			case Platform.TENCENT_PLATFORM:
				 
				 userNameTextView.setText(getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE).getString("userName", ""));
				 
				 break;	
			default:
				 break;
		}
		
		writeButton = (ImageButton) findViewById(R.id.writeMicroblogBtn);
		
		writeButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent();
				
				intent.setClass(MBlogListActivity.this, WriteMBlogActivity.class);
				
				startActivity(intent);
			}
		});
		
		refreshButton = (ImageButton) findViewById(R.id.refreshBtn);
		
		refreshButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				
				updateHomeTimeLine();
				
			}
		});
		
		//添加第一行的刷新行
		ListView listView = this.getListView();
		
		LinearLayout refreshRowView = new LinearLayout(this);

		String inflater = Context.LAYOUT_INFLATER_SERVICE;

		LayoutInflater vi = (LayoutInflater) this.getSystemService(inflater);

		vi.inflate(R.layout.mblog_list_refresh_row, refreshRowView, true);
			
		refreshRowView.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				updateHomeTimeLine();
				
			}
		});
		
		listView.addHeaderView(refreshRowView);
		
		firstStateText = (TextView) MBlogListActivity.this.findViewById(R.id.firstStateText);
		
		firstLoading = (ProgressBar) MBlogListActivity.this.findViewById(R.id.firstLoading);
		
		//最后一行的载入更多
		lastRowView = new LinearLayout(this);

		vi.inflate(R.layout.mblog_list_last_row, lastRowView, true);
			
		lastRowView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				
				loadOldMBlogs();
				
			}
		});
		
		lastStateText = (TextView) MBlogListActivity.this.findViewById(R.id.lastStateText);
		
		lastLoading = (ProgressBar) MBlogListActivity.this.findViewById(R.id.lastLoading);
		
		// 如果cache列表有至少一条微博再添加最后一行的载入更多，否则列表为空的话只有第一行的刷新
		if(CacheUtil.cacheMBlogList.size() >= 1){
			
			listView.addFooterView(lastRowView);
	
		}
		
		
		// 先从本地cache中读取数据
		arrayAdapter = new MBlogArrayAdapter(this, R.layout.mblog_item, CacheUtil.cacheMBlogList, platformType);
		
		this.setListAdapter(arrayAdapter);
	}
	
	/**
	 * 从服务器更新用户及其关注好友的状态 更新成功后缓存一份xml在本地
	 * 
	 */
	private void updateHomeTimeLine() {
		
		if(isLoading){
			
			Toast.makeText(this, "正在载入更多较早微博的信息，请稍后再试", Toast.LENGTH_SHORT).show();
			
			return;
			
		}else{
			
			isRefreshing = true;
			
			//将第一行刷新行的字改为载入中，同时显示刷新圆圈
			setRefreshRow(R.string.loading,View.VISIBLE);
			
			new Thread() {
				
				public void run() {
					
					try {
						// 先将xml或json缓存到本地，再从本地xml读取数据
//						URL url = new URL(getResources().getString(
//								R.string.server_hometimeline) + "?platformType=" + platformType);
//						
//						InputStream urlInputStream = url.openStream();
						
						FileOutputStream out = null;
						
						//根据微博平台决定保存路径
						switch (platformType) {
						
							case Platform.SINA_PLATFORM:
					        	
//								 out = MBlogListActivity.this.openFileOutput(MBlogListActivity.this.getString(R.string.status_list_sina_xml_cache),MODE_PRIVATE);
								
								 out = MBlogListActivity.this.openFileOutput(MBlogListActivity.this.getString(R.string.status_list_json_cache) + "sina.json",MODE_PRIVATE);
														 					 
								 Weibo weibo = OAuthConstant.getInstance().getWeibo();	
								 
								 CacheUtil.saveJsonCache(out, weibo.getFriendsTimelineJson());
								 
								 break;
								 
							case Platform.TENCENT_PLATFORM:
								
//								 out = MBlogListActivity.this.openFileOutput(MBlogListActivity.this.getString(R.string.status_list_tencent_xml_cache),MODE_PRIVATE);
								
								 out = MBlogListActivity.this.openFileOutput(MBlogListActivity.this.getString(R.string.status_list_json_cache) + "tencent.json",MODE_PRIVATE);
								
								 QWeiboSyncApi api = new QWeiboSyncApi();
								 
								 SharedPreferences preference = getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
								 
								 String result = api.getHomeMsg(OAuth.AppKey, OAuth.AppSecret, preference.getString("AccessToken", null),preference.getString("AccessTokenSecret", null), ResultType.ResultType_Json, PageFlag.PageFlag_First, 20, null);
								 
//								 System.out.println(result);
								 
								 CacheUtil.saveJsonCache(out,result);
								 
								 break;	
								 
							default:
								 break;
								 
						}

//						CacheUtil.saveURLXmlCache(out, urlInputStream);		
						
						// 更新本地缓存
//						CacheUtil.readDateFromLocalXmlCache(MBlogListActivity.this,platformType);
						CacheUtil.readDateFromLocalJsonCache(MBlogListActivity.this,platformType);
						
						//发送消息刷新UI
						sendMessage(UPDATE);
						
						// 不能直接用创建的线程刷新ui界面，否则会报android.view.ViewRoot$CalledFromWrongThreadException:
						// Only the original thread that created a view hierarchy
						// can touch its views.
//						MBlogListActivity.this.runOnUiThread(new Runnable() {
//							@Override
//							public void run() {
//								
//								mblogList = CacheUtil.cacheMBlogList;
//								
//								arrayAdapter.update(mblogList);
//								
//								MBlogListActivity.this.setListAdapter(arrayAdapter);
//								
//								//将第一行刷新行的字改为刷新，同时隐藏刷新圆圈
//								setRefreshRow(R.string.refresh,View.GONE);
//								
//							}
//						});
						
					} catch (Exception e) {
						
						e.printStackTrace();
						
						//在线程中绘制toast，一定要调用Looper.prepare()和Looper.loop()，不然会报异常
			        	//ERROR/AndroidRuntime(10325): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
			        	Looper.prepare(); 
			        	
						Toast.makeText(MBlogListActivity.this, "载入失败，请检查网络连接并稍后再试", Toast.LENGTH_SHORT).show();
						
						Looper.loop();	
						
						//发送消息刷新UI
						sendMessage(RESET_FIRST);
						
					}
				}
			}.start(); // 开始运行运行线程	
		}		
	}
	
	/**
	 * 载入较早的微博
	 * @throws WeiboException 
	 * @throws NumberFormatException 
	 */
	private void loadOldMBlogs(){
		
		if(isRefreshing){
			
			Toast.makeText(this, "正在刷新微博信息，请稍后再试", Toast.LENGTH_SHORT).show();
			
			return;
			
		}else{
			
			isLoading = true;
			
			setLastRow(R.string.loading, View.VISIBLE);
			
			//较早的微博不缓存在本地文件中，即本地文件的缓存始终是最近一次刷新时最新的20条
			switch (platformType) {
			
			    //新浪微博通过微博id界定较老的微博列表
				case Platform.SINA_PLATFORM:
		        	 
					 new Thread(){

						@Override
						public void run() {
							
							 Weibo weibo = OAuthConstant.getInstance().getWeibo();	
							
							 String lastMBlogId = ((MBlog) arrayAdapter.getItem(arrayAdapter.getCount() - 1)).getId();
								 
							 try {
								 
								 String result = weibo.getFriendsTimelineJSONString(Long.parseLong(lastMBlogId));
								 
								 if(mblogList == null)
									 mblogList = CacheUtil.cacheMBlogList;
								 
								 //返回的是id小于等于lastMBlogId的，所以第一条是重复的
								 List<MBlog> list = CacheUtil.transferSinaJSONStringToList(result);
								 
								 if(list.size() >= 1){
									 
									 list.remove(0);
									 
								 }
									 
								 mblogList.addAll(list);
								 
								 //发送消息刷新UI
								 sendMessage(ADD_OLD);
								 
							} catch (Exception e) {
								
								e.printStackTrace();
								
								//在线程中绘制toast，一定要调用Looper.prepare()和Looper.loop()，不然会报异常
					        	//ERROR/AndroidRuntime(10325): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
					        	Looper.prepare(); 
					        	
								Toast.makeText(MBlogListActivity.this, "载入失败，请检查网络连接并稍后再试", Toast.LENGTH_SHORT).show();
								
								Looper.loop();	
								
								//发送消息刷新UI
								sendMessage(RESET_LAST);
								
							} 
						}
						
					}.start();
	 
					 break;
				
				//腾讯微博通过微博时间戳界定较老的微博列表
				case Platform.TENCENT_PLATFORM:
					 
					new Thread(){

						@Override
						public void run() {
							
							 String lastMBlogTimeStamp = TimeUtil.formatDateToTencentString(((MBlog) arrayAdapter.getItem(arrayAdapter.getCount() - 1)).getCreated_at());
								 
							 try {
								 QWeiboSyncApi api = new QWeiboSyncApi();
								 
								 SharedPreferences preference = getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
								 
								 String str = api.getHomeMsg(OAuth.AppKey, OAuth.AppSecret, preference.getString("AccessToken", null),preference.getString("AccessTokenSecret", null), ResultType.ResultType_Json, PageFlag.PageFlag_Next, 20, lastMBlogTimeStamp);
								 
								 if(mblogList == null)
									 mblogList = CacheUtil.cacheMBlogList;
								 
								 mblogList.addAll(CacheUtil.transferTencentJSONStringToList(str));
								 
								 //发送消息刷新UI
								 sendMessage(ADD_OLD);
								 
							} catch (Exception e) {
								
								e.printStackTrace();
								
								//在线程中绘制toast，一定要调用Looper.prepare()和Looper.loop()，不然会报异常
					        	//ERROR/AndroidRuntime(10325): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
					        	Looper.prepare(); 
					        	
								Toast.makeText(MBlogListActivity.this, "载入失败，请检查网络连接并稍后再试", Toast.LENGTH_SHORT).show();
								
								Looper.loop();	
								
								//发送消息刷新UI
								sendMessage(RESET_LAST);
								 
							} 
						}
						
					 }.start();
					 
					 break;	
					 
				default:
					 break;
					 
			}
		}		
	}
	
	/**
	 * 设置第一行刷新行的状态
	 */
	private void setRefreshRow(int stateStringId,int visibility){
			
		if(firstStateText == null)
			firstStateText = (TextView) MBlogListActivity.this.findViewById(R.id.firstStateText);
		
		if(firstLoading == null)
			firstLoading = (ProgressBar) MBlogListActivity.this.findViewById(R.id.firstLoading);
		
		firstStateText.setText(MBlogListActivity.this.getResources().getString(stateStringId));
			
		firstLoading.setVisibility(visibility);
		
	}

	/**
	 * 设置最后一行载入更多行的状态
	 */
	private void setLastRow(int stateStringId,int visibility){
		if(lastStateText == null)
			lastStateText = (TextView) MBlogListActivity.this.findViewById(R.id.lastStateText);
		
		if(lastLoading == null)
			lastLoading = (ProgressBar) MBlogListActivity.this.findViewById(R.id.lastLoading);
		
		lastStateText.setText(MBlogListActivity.this.getResources().getString(stateStringId));
			
		lastLoading.setVisibility(visibility);
		
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			
			Intent intent = new Intent();
			
			intent.setClass(this, MBlogPlatformListActivity.class);
			
			this.finish();	
			
			startActivity(intent);
			
		}

		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 发送消息
	 * @param value
	 */
	private void sendMessage(int value){
		
		 Message msg = new Message();
		
		 Bundle bundle = new Bundle();
			
		 bundle.putInt("flag", value);
			
		 msg.setData(bundle);
			
		 handler.sendMessage(msg);
		 
	}
	
	//刷新微博
	private static final int UPDATE = 0;
	//载入更早的微博
	private static final int ADD_OLD = 1;
	//重置第一行刷新行
	private static final int RESET_FIRST = 2;
	//重置
	private static final int RESET_LAST = 3;

	private class UIHandler extends Handler{
		
		@Override
		public void handleMessage(Message msg) {
			
			super.handleMessage(msg);
			
			int flag = msg.getData().getInt("flag");	
			
			switch (flag) {
				
				case UPDATE:
					
					 System.out.println("刷新");
					 
					 mblogList = CacheUtil.cacheMBlogList;
					
					 arrayAdapter.update(mblogList);
					
					 //将第一行刷新行的字改为刷新，同时隐藏刷新圆圈
					 setRefreshRow(R.string.refresh,View.GONE);
					 
					 // 如果cache列表有至少一条微博再添加最后一行的载入更多，否则列表为空的话只有第一行的刷新
					 if(CacheUtil.cacheMBlogList.size() >= 1){
							
							MBlogListActivity.this.getListView().addFooterView(lastRowView);
					
					 }
					
					 isRefreshing = false;
					 
					 break;
					 
				case ADD_OLD:
					
					 System.out.println("载入更多");
					 
					 arrayAdapter.update(mblogList);
					 
					 //将最后一行刷新行的字改为载入更多，同时隐藏刷新圆圈
					 setLastRow(R.string.loadMore,View.GONE);
					 
					 isLoading = false;
					 
					 break;
				
				case RESET_FIRST:
					 
					 System.out.println("复原第一行");
					
					 setRefreshRow(R.string.refresh,View.GONE);
					 
					 isRefreshing = false;
					 
					 isLoading = false;
					 
					 break;
				
				case RESET_LAST:
					 
					 System.out.println("复原最后一行");
					
					 setLastRow(R.string.loadMore,View.GONE);
					 
					 isRefreshing = false;
					 
					 isLoading = false;
					 
					 break;
					 
				default:
					 break;
			};
		}
		
	}
}